package it.koutifaris.travianmap.info;

import it.koutifaris.travianmap.info.TroopsLoader.OnTroopHandler;
import it.koutifaris.travianmap.model.Tribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;

public class Troops {

	private static final Troops INSTANCE = new Troops();

	private final EnumMap<Tribe, List<Troop>> troopsPerTribe;
	private final List<Troop> allTroops;

	private Troops() {
		troopsPerTribe = new EnumMap<Tribe, List<Troop>>(Tribe.class);
		allTroops = new ArrayList<Troop>();
		new TroopsLoader().load(new OnTroopHandlerImpl());
	}

	public static Troops troops() {
		return INSTANCE;
	}

	public List<Troop> getTroopsOfTribe(Tribe tribe) {
		return Collections.unmodifiableList(getTroopsPerTribe(tribe));
	}

	private void addTroop(Troop troop) {
		allTroops.add(troop);
		getTroopsPerTribe(troop.tribe()).add(troop);
	}

	private List<Troop> getTroopsPerTribe(Tribe tribe) {
		List<Troop> troopList = troopsPerTribe.get(tribe);
		if (troopList == null) {
			troopList = new ArrayList<Troop>();
			troopsPerTribe.put(tribe, troopList);
		}

		return troopList;
	}

	private class OnTroopHandlerImpl implements OnTroopHandler {

		@Override
		public void onTroop(Troop troop) {
			addTroop(troop);
		}

	}
}
